package cn.hx.malluser.controller;

import cn.hx.malluser.entity.UmsMember;
import cn.hx.malluser.entity.UmsMemberLevel;
import cn.hx.malluser.service.UmsMemberLevelService;
import cn.hx.malluser.service.UmsMemberService;
import cn.hx.malluser.util.JwtUtils;
import cn.hx.malluser.vo.UmsMemberVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.netflix.ribbon.proxy.annotation.Http;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.spi.http.HttpContext;
import java.net.HttpCookie;
import java.util.HashMap;
import java.util.Map;

@Controller
@CrossOrigin(allowCredentials = "true")
public class UmsMemberLoginController {

    @Autowired
    private UmsMemberService umsMemberService;

    @Autowired
    private UmsMemberLevelService levelService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @PostMapping("/login")
    @ResponseBody
    public Map<String, Object> login(String phone, String password, HttpServletResponse response, HttpServletRequest request) {
        UmsMember umsMember = umsMemberService.queryByPhoneAndPwd(phone, password);
        Map<String, Object> map = new HashMap<>();
        if (umsMember == null) {
            map.put("msg", "error");
            map.put("data", null);
        }else {
            map.put("msg", "success");
            Long id = umsMember.getId();
            UmsMemberLevel umsMemberLevel = levelService.getById(umsMember.getMemberLevelId());
            UmsMemberVo vo = UmsMemberVo.init(umsMember, umsMemberLevel);
            redisTemplate.opsForValue().set("user_" + id, vo);
            map.put("data", id);
            Map<String,Object> map1 = new HashMap<>();
            map1.put("user",vo);
            Object preUrl = redisTemplate.opsForValue().get("preUrl");
            if (preUrl != null) {
                preUrl = preUrl.toString().substring(0, preUrl.toString().lastIndexOf("/")) + "?token=" + JwtUtils.getToken(map1);
            }
            System.out.println(preUrl);
            map.put("preUrl",preUrl);
            Cookie cookie = new Cookie("token", JwtUtils.getToken(map1));
            response.addCookie(cookie);
        }
        return map;
    }

    @GetMapping("/logout/{id}")
    public String logout(@PathVariable Long id) {
        redisTemplate.delete("user_" + id);
        return "redirect:/user/login";
    }
}
